package com.vcredit.creditcat.service.income;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.vcredit.creditcat.dto.income.MyIncomeDto;
import com.vcredit.creditcat.enumtype.AbilityEnum;
import com.vcredit.creditcat.model.CustAbility;
import com.vcredit.creditcat.model.CustProduct;
import com.vcredit.creditcat.model.CustRecommendCard;
import com.vcredit.creditcat.model.IncomeLog;
import com.vcredit.creditcat.model.IncomeLogExt;
import com.vcredit.creditcat.model.IncomeType;
import com.vcredit.creditcat.model.MerchantProduct;
import com.vcredit.creditcat.model.Message;
import com.vcredit.creditcat.model.RecommendCard;
import com.vcredit.creditcat.model.WalletAmt;
import com.vcredit.creditcat.model.WalletAmtLog;
import com.vcredit.creditcat.service.CustAbilityService;
import com.vcredit.creditcat.service.CustRecommendCardService;
import com.vcredit.creditcat.service.MerchantProductService;
import com.vcredit.creditcat.service.MessageService;
import com.vcredit.creditcat.service.RecommendCardService;
import com.vcredit.creditcat.service.product.CustLoanProductService;
import com.vcredit.creditcat.service.wallet.WalletAmtLogService;
import com.vcredit.creditcat.service.wallet.WalletAmtService;
import com.vcredit.creditcat.util.Utility;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.exception.BaseException;
import com.vcredit.framework.util.JacksonUtil;

@Service
public class MyIncomeService {
	
	private static final Logger LOG = LoggerFactory.getLogger(MyIncomeService.class);
	
	private static final String INCOME_MSG_TITLE = "最新特权收益";

	@Autowired
	private IncomeLogService incomeLogService;

	@Autowired
	private WalletAmtService walletAmtService;

	@Autowired
	private WalletAmtLogService walletAmtLogService;
	
	@Autowired
	private IncomeTypeService incomeTypeService;
	
	@Autowired
	private CustAbilityService custAbilityService;
	
	@Autowired
	private MessageService messageService;
	
	@Autowired
	private MerchantProductService merchantProductService;
	
	@Autowired
	private CustLoanProductService custLoanProductService;
	
	@Autowired
	private RecommendCardService recommendCardService;
	
	@Autowired
	private CustRecommendCardService custRecommendCardService;

	/**
	 * 领取收益
	 * 
	 * @author zhaoqi01
	 * @param custId
	 * @throws BaseException
	 */
	@Log
	@Transactional(propagation = Propagation.REQUIRED)
	public void drawIncome(Long incomeLogId, Long custId) throws Exception {
		try {
			IncomeLog incomeLog = incomeLogService.findById(incomeLogId);
			
			if (incomeLog == null
					|| incomeLog.getCustId().longValue() != custId.longValue()
					|| incomeLog.getStatus() == 1) {
				throw new BaseException("领取收益出错!!");
			}
			
			Date date = new Date();
			// 用户钱包余额操作
			WalletAmt walletAmt = new WalletAmt(custId, null, null, null);
			List<WalletAmt> walletAmtList = walletAmtService.find(walletAmt);
			if(Utility.isNullOrEmpty(walletAmtList)) {
				walletAmt.setAmt(incomeLog.getAmt());
				walletAmt.setCreateTime(date);
				walletAmt.setUpdateTime(date);
				walletAmtService.insert(walletAmt);
			} else {
				walletAmt = walletAmtList.get(0);
				walletAmt.setAmt(walletAmt.getAmt() + incomeLog.getAmt());
				walletAmtService.update(walletAmt);
			}
			
			// 保存用户余额操作记录
			IncomeType incomeType = incomeTypeService.findById(incomeLog.getIncomeId());
			int type = incomeType.getIncomeType() == 0 ? 1 : 0;
			walletAmtLogService.insert(new WalletAmtLog(custId, type, incomeLog.getAmt(),
					null, null, date, date));
			
			// 更新领取状态为已领取
			incomeLog.setStatus(1);
			incomeLogService.update(incomeLog);
			
		} catch (Exception e) {
			LOG.error("------------领取收益出错!! param {incomeLogId="
								+ incomeLogId + ",custId=" + custId + "}",e);
			throw e;
		}
	}

	/**
	 * 我的收益列表
	 * @author zhaoqi01
	 * @param custId
	 * @return
	 */
	public List<MyIncomeDto> listIncome(Long custId) {
		List<MyIncomeDto> resultList = new ArrayList<MyIncomeDto>();
		List<IncomeLogExt> myIncome = incomeLogService.findMyIncome(custId);
		for (IncomeLogExt ext : myIncome) {
			resultList.add(new MyIncomeDto(ext.getId(), ext.getType()
					.getIncomeDesc(), ext.getType().getIncomeIcon(),
					ext.getAmt(), ext.getStatus(),
					ext.getCreateTime()));
		}
		return resultList;
	}
	
	/**
	 * 新增收益
	 * incomeId 收益类型id
	 * @author zhaoqi01
	 * @param custId
	 * @param incomeType
	 * @param incomeId
	 * @throws Exception 
	 */
	@Log
	@Transactional(propagation=Propagation.REQUIRED)
	public boolean addIncome(Long custId, int incomeId) throws Exception {
		// 查询用户的等级，获取能得到的收益
		CustAbility custAbility = custAbilityService.findMaxAbilityByCustId(custId);
		if(custAbility == null) {
			return false;
		}
		Long amt = this.getAbilityEnumByCode(custAbility.getAbilityId()).getAmt();
		
		// 新增收益
		Date date = new Date();
		incomeLogService.insert(new IncomeLog(custId, amt, incomeId, 0, date, date));
		
		// 查询收益类型详情信息
		IncomeType incomeType = incomeTypeService.findById(incomeId);
		
		// 新增收益消息
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("iconUrl", incomeType.getIncomeIcon());
		map.put("name", INCOME_MSG_TITLE);
		map.put("desc", incomeType.getIncomeDesc());
		map.put("amt", amt);
		map.put("createTime", date);
		messageService.insert(new Message(4, JacksonUtil.Obj2Json(map), custId, date, 1, date, date));
		
		//添加办卡或贷款记录
		if(incomeType.getIncomeType()==0){			
			MerchantProduct product = merchantProductService.findById(incomeType.getProductCardId());
			if(product==null){
				throw new Exception("收益对应的贷款产品不存在！");
			}
			CustProduct custProduct = new CustProduct();
			custProduct.setCustId(custId);
			custProduct.setProductId(product.getProductId());
			custLoanProductService.insert(custProduct);
		}else if(incomeType.getIncomeType()==1){
			RecommendCard card = recommendCardService.findById(incomeType.getProductCardId());
			if(card==null){
				throw new Exception("收益对应的信用卡不存在！");
			}
			CustRecommendCard custRecommendCard = new CustRecommendCard();
			custRecommendCard.setCustId(custId);
			custRecommendCard.setCardId(card.getCardId());
			custRecommendCard.setCardName(card.getBank());
			custRecommendCardService.insert(custRecommendCard);
		}
		//添加特权
		custAbilityService.toAddAbility(custId);
		return true;
	}

	public AbilityEnum getAbilityEnumByCode(Long code) {
		for(AbilityEnum abilityEnum : AbilityEnum.values()) {
			if(abilityEnum.getCode() == code.longValue()) {
				return abilityEnum;
			}
		}
		return null;
	}
	
	 public BigDecimal getAccumulatedIncome(Long custId){
		  return incomeLogService.getAccumulatedIncome(custId);
	  }
}
